package com.im.service.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.im.service.common.Result;
import com.im.service.domain.dto.LoginDTO;
import com.im.service.domain.entity.ImUser;
import com.im.service.mapper.ImUserMapper;
import com.im.service.service.ImLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author liuzhiqiang
 */
@Service
public class ImLoginServiceImpl implements ImLoginService {

    @Autowired
    private ImUserMapper imUserMapper;

    @Override
    public Result<SaTokenInfo> login(LoginDTO loginDTO) {
        ImUser imUser = imUserMapper.selectOne(
                Wrappers.lambdaQuery(ImUser.class)
                        .eq(ImUser::getUsername, loginDTO.getUsername())
                        .eq(ImUser::getPassword, loginDTO.getPassword())
                        .last("limit 1")
        );
        if (ObjUtil.isNull(imUser)) {
            return Result.error(1000, "用户不存在或密码错误");
        }
        StpUtil.login(imUser.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Result.okData(tokenInfo);
    }
}
